<?php
/**
 * Created by PhpStorm.
 * User: Da Xiong
 * Date: 2019/2/21
 * Time: 16:58
 */

namespace App\HttpController\Admin;

use App\Model\AdminsOpenidModel;
use App\Model\TmplmsgsModel;
use App\Model\WechatsModel;
use App\Utility\Cache;
use App\Utility\MiniProgram;
use Carbon\Carbon;

class WechatController extends AuthController
{

    /**
     * 获取列表
     */
    public function index(){
        $request = $this->request();
        $page = (int)$request->getRequestParam('page')??1;
        $applet = $request->getRequestParam('applet')??'';
        if(!$applet){
            return $this->writeJson(1,null,'参数不正确！');
        }
        $wechatModel = new WechatsModel();
        $list = $wechatModel->where('name',$applet)->paginate($page);

        //获取用户openID
        $adminOpenid = (new AdminsOpenidModel())->getAdminOpenid($applet,$this->userid);
        //获取用户可推送模板id数量

        //判断是否有可以formId
        $cache =  new Cache();
        //根据openid取找到相应的openid的formid的集合，先删除该集合已过期的所有的formid,
        $cache->zRemRangeByScore($adminOpenid,0,time()+10);
        //然后取集合的成员数
        $list['count_formid'] = $cache->zCard($adminOpenid);
        return $this->writeJson(0,$list,'ok');
    }


    /**
     * 新增/更新
     */
    public function update(){
        $request = $this->request();
        $params = $request->getRequestParam();
        if(!isset($params['name'])){
            return $this->writeJson(1,null,'参数不正确！');
        }
        $wechatModel = new WechatsModel();
        if($params['id']){
            //更新
            $idInfo = $wechatModel->find((int)$params['id']);
            if(!$idInfo){
                return $this->writeJson(1,null,'更新失败，数据不存在！');
            }
            if($wechatModel->update($params)){
                return $this->writeJson(0,null,'更新成功');
            }
        }else{
            //新增
            $params['created_at'] = Carbon::now();
            $idInfo = $wechatModel->create($params);
            if($idInfo){
                return $this->writeJson(0,null,'新增成功');
            }
        }
        return $this->writeJson(1,null,'系统出错了');
    }


    /**
     * 删除
     * @return bool
     * @throws \Throwable
     */
    public function destroy(){
        $request = $this->request();
        $id = $request->getRequestParam('id');
        $wechatModel = new WechatsModel();
        $wechatModel->destroy($id);
        return $this->writeJson(0);
    }

    /**
     * 模板推送，手机预览
     */
    public function preview(){
        $request = $this->request();
        $id = $request->getRequestParam('id') ?: 0;

        $wechatsModel = new WechatsModel();
        $wechatsInfo = $wechatsModel->find($id);

        //获取configName-> TmplmsgsId信息
        $configModelName = $this->appletConfigModel($wechatsInfo['name']);
        $configModel = new $configModelName;
        $configTemplateId = $configModel->where('name','template_id')->first();
        //获取用户openID
        $adminOpenid = (new AdminsOpenidModel())->getAdminOpenid($wechatsInfo['name'],$this->userid);
        if(!$adminOpenid){
            return $this->writeJson(1,null,'请联系技术人员添加openID！');
        }
        //获取TmplmsgsModel
        $model = new TmplmsgsModel();
        $msg = $model->where('template_id',$configTemplateId['value'])->first();


        //判断是否有可以formId
        $cache =  new Cache();
        //根据openid取找到相应的openid的formid的集合，先删除该集合已过期的所有的formid,
        $cache->zRemRangeByScore($adminOpenid,0,time()+10);
        //然后取一个formid的值
        $formid_array = $cache->zRange($adminOpenid,0,0);

        if(count($formid_array) == 0){
            return $this->writeJson(1,null,'没有可用的FORMID了！');
        }
        $formid = $formid_array[0];

        $msg['keywords'][0]->keyword2 = $wechatsInfo['title'];
        $wechat = new MiniProgram($wechatsInfo['name']);
        $sendData = [
            'touser'      => $adminOpenid,
            'template_id' => $msg['template_id'],
            'page'        => $msg['page'].'?url='.$wechatsInfo['link'],
            'form_id'     => $formid,
            'data'        => $msg['keywords'][0],
            'emphasis_keyword' => '',
        ];
        $result = $wechat->sendTemplateMessage($sendData);
        if($result['errcode'] == 0){
            //从集合中移除该formid
            $cache->zrem($adminOpenid,$formid);
            //如果删除集合中过期的formid值后该集合为空，则删除对应的小程序的openid集合中的openid元素
            if($cache->zCard($adminOpenid) == 0) $cache->srem($wechatsInfo['name'],$wechatsInfo['name'].'*'.$adminOpenid);
            return $this->writeJson(0, null, '推送成功');
        }else{
            if(($result['errcode'] == 41028) || ($result['errcode'] == 41029)){
                //从集合中移除该formid
                $cache->zrem($adminOpenid,$formid);
                //如果删除集合中过期的formid值后该集合为空，则删除对应的小程序的openid集合中的openid元素
                if($cache->zCard($adminOpenid) == 0) $cache->srem($wechatsInfo['name'],$wechatsInfo['name'].'*'.$adminOpenid);
            }
            return $this->writeJson(1, $result, '推送失败，'.$result['chmsg']);
        }

    }
}
